package org.lex.keytool.ui.builder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

import javax.swing.tree.TreeModel;

import org.lex.collection.tree.ITreeNode;
import org.lex.collection.tree.SwingTreeModel;
import org.lex.collection.tree.TreeUtils;
import org.lex.collection.tree.builder.NodeData;
import org.lex.collection.tree.builder.TreeBuilder;
import org.lex.keytool.core.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MenuTreeBuilder {
	private static final Pattern DOT_SPLITTER = Pattern.compile(Pattern.quote("."));
	private Logger log = LoggerFactory.getLogger(MenuTreeBuilder.class);

	public TreeModel buildMenuTreeModel() {
		Collection<String> menus = TaskService.getInstance().getTaskNames();
		List<NodeData> datas = new ArrayList<NodeData>(menus.size());
		Object rootId = new Object();
		NodeData rootData = new NodeData(rootId, null, "Tasks");
		datas.add(rootData);
		for (String menu : menus) {
			String[] paths = DOT_SPLITTER.split(menu);
			log.trace("menu=[" + menu + "] --> " + Arrays.toString(paths));
			for (int i = paths.length - 1; i >= 0; i--) {
				NodeData nd = new NodeData();
				nd.data = paths[i];
				int idLen = 0;
				for (int j = 0; j <= i; j++) {
					idLen += paths[j].length();
				}
				idLen += i;
				nd.id = menu.substring(0, idLen);
				if (i > 0) {
					nd.parentId = paths[i - 1];
				} else {
					nd.parentId = rootId;
				}

				datas.add(nd);
			}
		}

		ITreeNode root = new TreeBuilder().buildTree(datas);
		log.info("Menu Tree:\n" + TreeUtils.print(root));
		return new SwingTreeModel(root);
	}
}
